package com.swak.boot.config.zookeeper.config;

import org.apache.curator.framework.CuratorFramework;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.ConfigurableEnvironment;

import com.swak.Constants;
import com.swak.boot.config.zookeeper.ZookeeperBuilder;
import com.swak.boot.config.zookeeper.ZookeeperProperties;
import com.swak.config.ConfigService;
import com.swak.zookeeper.ZookeeperConfig;
import com.swak.zookeeper.ZookeeperService;

/**
 * 开启zk配置
 * 
 * @author lifeng
 */
@ConditionalOnClass({ CuratorFramework.class, ZookeeperService.class })
@ConditionalOnProperty(prefix = Constants.APPLICATION_PREFIX, name = "enableZk", matchIfMissing = true)
@EnableConfigurationProperties(ZookeeperProperties.class)
public class ZookeeperConfigAutoConfiguration {

	/**
	 * 创建配置服务器
	 * 
	 * @param service
	 * @return
	 * @throws InterruptedException 
	 */
	@Bean
	@Primary
	public ConfigService zookeeperConfig(ZookeeperProperties properties) throws InterruptedException {
		return new ZookeeperConfig(ZookeeperBuilder.build(properties));
	}

	/**
	 * 监听配置的变化
	 * 
	 * @param service
	 * @return
	 * @throws InterruptedException 
	 */
	@Bean
	public ConfigWatcher ConfigWatcher(ConfigurableEnvironment environment, ZookeeperProperties properties)
			throws InterruptedException {
		return new ConfigWatcher(environment, ZookeeperBuilder.build(properties));
	}
}